#include "WeightQuery.h"
#include <QDebug>
#include <qjson/parser.h>
#include <qjson/serializer.h>
#include <QVariant>
#include <QVariantMap>



WeightQuery::WeightQuery(QObject *parent)
        : QObject(parent)
    {
       jsonQuery = "";
       httpQuery = "";
       manager = new QNetworkAccessManager(this);

        qDebug() << "Free WeightQuery created";
    }

WeightQuery::WeightQuery(QString auth_token, QObject *parent)
                : QObject(parent)
    {
        manager = new QNetworkAccessManager(this);
        setQuery(auth_token);
        qDebug() << "WeightQuery created:\n"
                 << httpQuery << jsonQuery;
    }

 void WeightQuery::setQuery(QString auth_token)
    {
        QVariantMap request;
        request.insert("auth_token", auth_token);

        QJson::Serializer serializer;
        QString json(serializer.serialize(request));

        jsonQuery = json;
        httpQuery = "http://127.0.0.1/dietservice?query=requestWeight";
       // httpQuery = LOGIN_HTTP_URL;
    }

 void WeightQuery::setQueryToAdd(QString auth_token, double weight)
 {
     QVariantMap request;
     request.insert("auth_token", auth_token);
     request.insert("weight", weight);

     QJson::Serializer serializer;
     QString json(serializer.serialize(request));

     jsonQuery = json;
     httpQuery = "http://127.0.0.1/dietservice?query=applyWeight";
 }


  WeightQuery::~WeightQuery()
    {

    }

  const QString& WeightQuery::getHttpQuery()
    {
        return httpQuery;
    }

  const QString& WeightQuery::getJsonQuery()
    {
        return jsonQuery;
    }

   void WeightQuery::doRequest()
    {
        if (httpQuery == "" || jsonQuery == "")
        {
            qDebug() << "WeightQuery: can't do request because query isn't set";
            return;
        }

        QNetworkRequest request;
        QUrl url(httpQuery);
        url.setPort(80);
        request.setUrl(url);

        QByteArray data(jsonQuery.toAscii(), jsonQuery.size());

        QNetworkReply *reply = manager->post(request, data);

        connect(manager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(onManagerFinished(QNetworkReply*)));
        connect(manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
                this, SLOT(onManagerSslErrors()));
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
                this, SLOT(onReplyError(QNetworkReply::NetworkError)));

        qDebug() << "WeightQuery did request:\n"
                 << httpQuery << jsonQuery;
    }


   void WeightQuery::doRequestToAdd()
    {
        if (httpQuery == "" || jsonQuery == "")
        {
            qDebug() << "WeightQuery: can't do request because query isn't set";
            return;
        }

        QNetworkRequest request;
        QUrl url(httpQuery);
        url.setPort(80);
        request.setUrl(url);

        QByteArray data(jsonQuery.toAscii(), jsonQuery.size());

        QNetworkReply *reply = manager->post(request, data);

        connect(manager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(onManagerFinishedToAdd(QNetworkReply*)));
        connect(manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
                this, SLOT(onManagerSslErrors()));
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
                this, SLOT(onReplyError(QNetworkReply::NetworkError)));

        qDebug() << "WeightToAddQuery did request:\n"
                 << httpQuery << jsonQuery;
    }



  void WeightQuery::onManagerFinished(QNetworkReply *reply)
    {
        QByteArray jsonResponseByteArray = reply->readAll();

        if (jsonResponseByteArray.size() > 0)
        {
            QString jsonResponse(jsonResponseByteArray);
            qDebug() << "Gotten response (json): " << jsonResponse;
            QJson::Parser parser;
            bool ok;
            QVariantMap result = parser.parse(QByteArray(jsonResponse.toAscii()), &ok).toMap();
            QString status("");
            QDate date;
            QString date_string;
            double weight;
            if (!ok)
            {
                qFatal("An error occured during parsing json with channel list");
            }
            else
            {
                status = result["status"].toString();
                date_string = result["date"].toString();

                //date = result["date"].toDate();
                date = QDate::fromString(date_string, "dd-MM-yyyy");
                QString str = date.toString("dd-MM-yyyy");
                qDebug()<<"DATE:"<<str;
                weight = result["weight"].toDouble();


            }

            emit responseReceived(status, date, weight);
        }
    }

 void WeightQuery::onReplyError(QNetworkReply::NetworkError error)
    {
        qDebug("Network error: %d \n", error);
        qDebug("onReplyError");
        emit errorWReceived();
    }

 void WeightQuery::onManagerSslErrors()
    {
        qDebug("ssl error \n");
        emit errorWReceived();
    }



 void WeightQuery::onManagerFinishedToAdd(QNetworkReply *reply)
   {
       QByteArray jsonResponseByteArray = reply->readAll();

       if (jsonResponseByteArray.size() > 0)
       {
           QString jsonResponse(jsonResponseByteArray);
           qDebug() << "Gotten response (json): " << jsonResponse;
           QJson::Parser parser;
           bool ok;
           QVariantMap result = parser.parse(QByteArray(jsonResponse.toAscii()), &ok).toMap();
           QString status("");
           double weight;
           if (!ok)
           {
               qFatal("An error occured during parsing json with channel list");
           }
           else
           {
               status = result["status"].toString();


           }

           emit responseReceived(status);
       }
   }




